package com.kexio.user.service.impl;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kexio.user.service.AuthService;
import com.kexio.user.service.PermissionService;
import com.kexio.user.service.RoleService;
import com.kexio.user.service.UserService;
import com.kexio.user.service.UserStatisticsService;

/**
 * 用户业务统计服务实现
 * 
 * 架构特点：
 * 1. 位于业务模块中，职责明确
 * 2. 直接注入服务依赖，不使用反射
 * 3. 所有依赖都在同一模块内，无循环依赖
 * 4. 真实数据来源，无模拟数据
 * 
 * @author Kexio Team
 * @since 2.2.0
 */
@Service
public class UserStatisticsServiceImpl implements UserStatisticsService {

    private static final Logger logger = LoggerFactory.getLogger(UserStatisticsServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private AuthService authService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public BusinessStatistics getBusinessStatistics() {
        logger.debug("获取综合业务统计 - 直接服务调用（无反射）");
        
        BusinessStatistics stats = new BusinessStatistics();
        stats.setTimestamp(LocalDateTime.now());
        
        try {
            Long totalUsers = userService.countTotalUsers();
            Long activeUsers = userService.countActiveUsers();
            Long onlineUsers = authService.getOnlineUserCount();
            
            logger.debug("用户统计: 总数={}, 活跃={}, 在线={}", totalUsers, activeUsers, onlineUsers);
            
            stats.setTotalUsers(totalUsers);
            stats.setActiveUsers(activeUsers);
            stats.setOnlineUsers(onlineUsers);
            
            TenantStatistics tenantStats = new TenantStatistics();
            tenantStats.setTotalTenants(userService.countTotalTenants());
            tenantStats.setActiveTenants(userService.countActiveTenants());
            tenantStats.setTenantUserCounts(userService.getTenantUserCounts());
            stats.setTenantStats(tenantStats);
            
            logger.debug("租户统计: 总数={}, 活跃={}", tenantStats.getTotalTenants(), tenantStats.getActiveTenants());
            
            Map<String, Long> permissionStats = new HashMap<>();
            permissionStats.put("system:user:*", permissionService.countPermissionsByPattern("system:user:*"));
            permissionStats.put("system:role:*", permissionService.countPermissionsByPattern("system:role:*"));
            permissionStats.put("system:menu:*", permissionService.countPermissionsByPattern("system:menu:*"));
            permissionStats.put("system:permission:*", permissionService.countPermissionsByPattern("system:permission:*"));
            stats.setPermissionUsageStats(permissionStats);
            
            logger.debug("权限统计: {}", permissionStats);
            
            Map<String, Long> roleStats = roleService.getRoleDistributionStats();
            stats.setRoleDistribution(roleStats);
            
            logger.debug("角色分布: {}", roleStats);
            
        } catch (Exception e) {
            logger.error("获取业务统计失败: {}", e.getMessage(), e);
            // 设置默认值，而不是抛出异常
            stats.setTotalUsers(0L);
            stats.setActiveUsers(0L);
            stats.setOnlineUsers(0L);
            stats.setPermissionUsageStats(new HashMap<>());
            stats.setRoleDistribution(new HashMap<>());
            stats.setTenantStats(new TenantStatistics());
        }
        
        return stats;
    }

    @Override
    public UserOverviewStatistics getUserOverview() {
        logger.debug("获取用户概览统计");
        
        UserOverviewStatistics overview = new UserOverviewStatistics();
        overview.setTimestamp(LocalDateTime.now());
        
        try {
            overview.setTotalUsers(userService.countTotalUsers());
            overview.setActiveUsers(userService.countActiveUsers());
            overview.setOnlineUsers(authService.getOnlineUserCount());
            
            // 计算禁用用户数 = 总用户数 - 活跃用户数（简化计算）
            Long disabledUsers = overview.getTotalUsers() - overview.getActiveUsers();
            overview.setDisabledUsers(Math.max(0L, disabledUsers));
            
            logger.debug("用户概览: 总数={}, 活跃={}, 在线={}, 禁用={}", 
                overview.getTotalUsers(), overview.getActiveUsers(), 
                overview.getOnlineUsers(), overview.getDisabledUsers());
                
        } catch (Exception e) {
            logger.error("获取用户概览统计失败: {}", e.getMessage(), e);
            overview.setTotalUsers(0L);
            overview.setActiveUsers(0L);
            overview.setOnlineUsers(0L);
            overview.setDisabledUsers(0L);
        }
        
        return overview;
    }

    @Override
    public Map<String, Long> getRoleDistribution() {
        logger.debug("获取角色分布统计");
        
        try {
            Map<String, Long> distribution = roleService.getRoleDistributionStats();
            logger.debug("角色分布结果: {}", distribution);
            return distribution;
            
        } catch (Exception e) {
            logger.error("获取角色分布统计失败: {}", e.getMessage(), e);
            return new HashMap<>();
        }
    }

    @Override
    public TenantStatistics getTenantStatistics() {
        logger.debug("获取租户统计数据");
        
        TenantStatistics tenantStats = new TenantStatistics();
        
        try {
            tenantStats.setTotalTenants(userService.countTotalTenants());
            tenantStats.setActiveTenants(userService.countActiveTenants());
            tenantStats.setTenantUserCounts(userService.getTenantUserCounts());
            
            logger.debug("租户统计: 总数={}, 活跃={}, 分布={}", 
                tenantStats.getTotalTenants(), tenantStats.getActiveTenants(), 
                tenantStats.getTenantUserCounts());
                
        } catch (Exception e) {
            logger.error("获取租户统计失败: {}", e.getMessage(), e);
            tenantStats.setTotalTenants(0L);
            tenantStats.setActiveTenants(0L);
            tenantStats.setTenantUserCounts(new HashMap<>());
        }
        
        return tenantStats;
    }

    @Override
    public Map<String, Long> getPermissionUsageStatistics() {
        logger.debug("获取权限使用统计");
        
        Map<String, Long> permissionStats = new HashMap<>();
        
        try {
            permissionStats.put("system:user:*", permissionService.countPermissionsByPattern("system:user:*"));
            permissionStats.put("system:role:*", permissionService.countPermissionsByPattern("system:role:*"));
            permissionStats.put("system:menu:*", permissionService.countPermissionsByPattern("system:menu:*"));
            permissionStats.put("system:permission:*", permissionService.countPermissionsByPattern("system:permission:*"));
            permissionStats.put("system:dept:*", permissionService.countPermissionsByPattern("system:dept:*"));
            
            logger.debug("权限统计结果: {}", permissionStats);
            
        } catch (Exception e) {
            logger.error("获取权限使用统计失败: {}", e.getMessage(), e);
        }
        
        return permissionStats;
    }
}
